<template>
	<div class="content" v-if="paper">
		<div class="mask" v-if="tipmain.openmask">
			<div class="popup borderbox" v-if="tipmain.dialogStatus">
				<div class="tabs">
					<div class="item-tab">确认信息</div>
					<img class="btn-close" @click="cancel()" src="../../../assets/img/commen/icon-close.png" />
				</div>
				<div class="text">正在考试中,是否确认返回?</div>
				<div class="button">
					<div class="confirm" style="cursor: pointer" @click="confirm()">
						确认
					</div>
					<div class="cancel" style="cursor: pointer" @click="cancel()">
						取消
					</div>
				</div>
			</div>
			<div class="popup borderbox" v-if="tipmain.submitTip">
				<div class="tabs">
					<div class="item-tab">确认信息</div>
					<img class="btn-close" @click="cancel()" src="../../../assets/img/commen/icon-close.png" />
				</div>
				<div class="text" v-if="tipmain.surplus !== 0">
					还有{{ tipmain.surplus }}道题未做，确认要交卷吗？
				</div>
				<div class="text" v-else>确认要交卷吗？</div>
				<div class="button">
					<div class="confirm" style="cursor: pointer" @click="submitHandle()">
						确定
					</div>
					<div class="cancel" style="cursor: pointer" @click="cancel()">
						继续答题
					</div>
				</div>
			</div>
			<div class="popup borderbox" v-if="tipmain.readTip">
				<div class="tabs">
					<div class="item-tab">交卷提示</div>
					<img class="btn-close" @click="cancel()" src="../../../assets/img/commen/icon-close.png" />
				</div>
				<div class="text">本次考试已完成，请等待阅卷后查看成绩</div>
				<div class="button">
					<div class="confirm" style="cursor: pointer" @click="ok()">好的</div>
				</div>
			</div>
		</div>
		<div class="navheader">
			<div class="top">
				<div class="top-left" @click="goBack()">
					<img class="icon-back" src="../../../assets/img/commen/icon-back-h.png" />{{ paper.paperName }}
				</div>
				<div class="top-right">

					<div class="score-info">
						合格分：<span style="color:#e6a23c;">{{ paper.jigeScore }}分/{{ paper.totalScore }}分</span>
					</div>
					<div v-if="!flag" class="remaining-time">
						剩余时间：
						<span
							style="color:#f34343;">{{ remainingTime.hr }}时{{ remainingTime.min }}分{{ remainingTime.sec }}秒</span>
					</div>
					<div class="button" @click="submitAll" v-if="paperstatus===0">
						立即交卷
					</div>
					<div class="buttonover" v-else>
						已结束
					</div>
				</div>
			</div>
		</div>
		<div class="project-box">
			<div class="left-box" :style="{width:isshowcard?'300px':'0'}">
				<div class="left-boxdiv">
					<div class="btns">
						<div class="btntitle">
							答题卡
						</div>
					</div>
					<NumberSheet v-if="qidArr" :qidArr="qidArr" @change="changeQid"></NumberSheet>
				</div>

			</div>
			<div class="right-box" :style="{width:isshowcard?'870px':'1200px'}">
				<div class="tosmbtn">
					<i :class="isshowcard?'el-icon-arrow-left':'el-icon-arrow-right'" @click="tochgcard"></i>
				</div>
				<div class="btns">
					<div v-if="item" v-for="(item,index) in subjects" class="btn-title"
						:class="{active:subjectindex==index}" @click="setPoject(index)">
						{{item.tXName}}
					</div>
				</div>
				<div class="questions-box" ref="questionsbox">
					<template v-for="(item,index) in subjects">
						<template v-if="item">
							<div v-show="subjectindex==index && item.tXName==='选择题'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-choice :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-choice>
								</div>
							</div>
							<div v-show="subjectindex==index && item.tXName==='填空题'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-input :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-input>
								</div>
							</div>
							<div v-show="subjectindex==index && item.tXName==='多选题'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-select :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-select>
								</div>
							</div>
							<div v-show="subjectindex==index && item.tXName==='判断题'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-judge :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-judge>
								</div>
							</div>
							<div v-show="subjectindex==index && item.tXName==='简答题'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-qa :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-qa>
								</div>
							</div>
							<div v-show="subjectindex==index && item.tXName==='名词解释'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-qa :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-qa>
								</div>
							</div>
							<div v-show="subjectindex==index && item.tXName==='论述题'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-qa :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-qa>
								</div>
							</div>
							<div v-show="subjectindex==index && item.tXName==='综合分析题'">
								<div class="tabtitle">{{sortword(item.tXSort)}}
									{{item.tXName}}（{{item.tXTypeEnumDescription}}）</div>
								<div class="item" :ref="'que'+index+qindex" v-for="(question, qindex) in item.list">
									<question-qa :subindex="index" :qindex="qindex" :questiontype="item.tXName"
										:question="question" @update="questionUpdate">
									</question-qa>
								</div>
							</div>
						</template>

					</template>
					<div v-if="shownext" class="nextbutton" @click="tonextindex">
						进入下一题型 <i style="margin-left:10px;" class="el-icon-right"></i>
					</div>
				</div>

			</div>
		</div>

	</div>
</template>
<script>
	import { mapState } from 'vuex'
	import QuestionChoice from '../../../components/choice2.vue'
	import QuestionSelect from '../../../components/select2.vue'
	import QuestionInput from '../../../components/input2.vue'
	import QuestionQa from '../../../components/qa2.vue'
	import QuestionJudge from '../../../components/judge2.vue'
	import QuestionCap from '../../../components/cap.vue'
	import NumberSheet from "../../../components/numbersheet2.vue";
	import Utils from "@/js/utils";

	export default {
		components: {
			QuestionChoice,
			QuestionSelect,
			QuestionInput,
			QuestionQa,
			QuestionJudge,
			QuestionCap,
			NumberSheet
		},
		data() {
			return {
				paper: null,
				paperstatus: 0,
				remainingTime: {
					all: 0,
					day: 0,
					hr: 0,
					min: 0,
					sec: 0,
				},
				timer: null,
				flag: false,
				qidArr: [],
				subjectindex: null,
				subjects: [],
				tipmain: {
					openmask: false,
					surplus: null,
					submitTip: false,
					dialogStatus: false,
					readTip: false
				},
				isshowcard: true,
				shownext: true
			}
		},
		watch: {
			qidArr: {
				handler: function(newarr, oldarr) {
					let nofinish = 0;
					newarr.map(item => {
						if (item && item.config && item.config.length > 0) {
							item.config.map(it => {
								if (!it) {
									nofinish++
								}
							})
						}
					})
					this.tipmain.surplus = nofinish
				},
				immediate: true,
				deep: true
			}
		},
		mounted() {
			this.startlink()
			this.remainingTime.all = Date.parse(
				new Date(this.$route.query.endtime)
			)

			this.timer = setInterval(() => {
				if (this.flag) {
					this.timer && clearInterval(this.timer)
				} else {
					this.countdown()
				}
			}, 1000)
			this.getData()
			window.addEventListener('beforeunload', e => this.beforeunloadHandler(e));
			
			
		},
		beforeDestroy() {
			this.timer && clearInterval(this.timer)
			window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e));
		},
		methods: {
			startlink(){
				var wsServer = 'ws://192.168.0.177:8080/websocket/qkws/kaoShiSocket?flag=0&examId='+this.$route.query.examinationId+'&userId='+this.$route.query.userId+'&token='+Utils.getToken();
				console.log({wsServer})
				
				var websocket = new WebSocket(wsServer);
				
				websocket.onopen = function (evt) {
				
				    console.log("Connected to WebSocket server.");
				
				    // websocket.send('open#'+username+'#'+book);
					websocket.send('Authorization: Bearer ' + Utils.getToken());
				
				};

				websocket.onclose = function (evt) {
				
				    console.log("Disconnected");
				
				};
				
				websocket.onmessage = function (evt) {
				
				    var data=JSON.parse(evt.data)
				
				    console.log(data)
				
				    if(data.msg=='useropen'){
				
				    }
				};
				
				websocket.onerror = function (evt, e) {
				
				    console.log('Error occured: ' + evt.data);
				
				};
				// websocket.send('edit#'+book);
			},
			sortword(index) {
				switch (index) {
					case 1:
						return '一';
					case 2:
						return '二';
					case 3:
						return '三';
					case 4:
						return '四';
					case 5:
						return '五';
					case 6:
						return '六';
					case 7:
						return '七';
					case 8:
						return '八';
					case 9:
						return '九';
					case 10:
						return '十';
					case 11:
						return '十一';
					case 12:
						return '十二';
					case 13:
						return '十三';
					case 14:
						return '十四';
					default:
						return '';
				}
			},
			tonextindex() {
				try {
					this.subjects.map((item, index) => {
						if (index > this.subjectindex && item) {
							this.subjectindex = index
							if (this.subjectindex == this.subjects.length - 1) {
								this.shownext = false
							}
							throw ('break')
						}
					})
				} catch (e) {
				}
			},
			beforeunloadHandler(e) {
				e.returnValue = '刷新或关闭页面，可能部分题目未保存';
			},
			tochgcard() {
				this.isshowcard = !this.isshowcard
			},
			changeQid(tindex, qindex) {
				this.subjectindex = tindex
				this.$nextTick(() => {
					this.$refs["questionsbox"].scrollTop = this.$refs["que" + tindex + qindex][0].offsetTop - this
						.$refs[
							"que" + tindex + '0'][0].offsetTop
				})
			},
			setPoject(n) {
				this.subjectindex = n
				if (this.subjectindex == this.subjects.length - 1) {
					this.shownext = false
				} else {
					this.shownext = true
				}
			},
			getData() {
				this.$api.Examination.JoinRecord(this.$route.query)
					.then(res => {
						const data = res.data
						let subjects = []
						let qidArr = []
						for (let i in data.allSubjects) {
							if (!data.allSubjects[i].tXName || !data.allSubjects[i].list) {
								continue
							}
							subjects[data.allSubjects[i].tXSort] = data.allSubjects[i]
							let qnums = []
							let qcons = []
							let qans = []
							let qunionids = []
							data.allSubjects[i].list.map((q, qi) => {
								qnums.push(q.weight)
								qunionids.push(q.examAnswerId)
								if (q.userAnswer !== undefined && q.userAnswer !== '') {
									qcons.push(true)
									qans.push(q.userAnswer)
								} else {
									qcons.push(false)
									qans.push(null)
								}
							})
							qidArr[data.allSubjects[i].tXSort] = {
								name: data.allSubjects[i].tXName,
								score: data.allSubjects[i].tXSubjectSum,
								arr: qnums,
								config: qcons,
								answer: qans,
								qunionids
							}
						}
						this.subjects = subjects
						for (let j = 0; j < subjects.length; j++) {
							if (subjects[j]) {
								this.subjectindex = j
								break
							}
						}
						this.paper = data.subjectInfo
						document.title = data.subjectInfo.paperName
						this.qidArr = qidArr
					})
					.catch(e => {
						this.$message.error(e.msg)
					})
			},
			//倒计时
			countdown() {
				const end = parseInt(this.remainingTime.all)
				const now = Date.parse(new Date())
				const msec = end - now
				if (msec < 0) {
					this.flag = true
					this.finish()
					return
				}
				let day = parseInt(msec / 1000 / 60 / 60 / 24)
				let hr = parseInt((msec / 1000 / 60 / 60) % 24)
				let min = parseInt((msec / 1000 / 60) % 60)
				let sec = parseInt((msec / 1000) % 60)
				this.remainingTime.day = day
				this.remainingTime.hr = hr > 9 ? hr : '0' + hr
				this.remainingTime.min = min > 9 ? min : '0' + min
				this.remainingTime.sec = sec > 9 ? sec : '0' + sec
				const that = this
				if (min >= 0 && sec >= 0) {
					//倒计时结束关闭订单
					if (min === 0 && sec === 0 && hr === 0) {
						that.flag = true
						this.finish()
						return
					}
				}
			},
			questionUpdate(subindex, qindex, answer, eqid) {
				if (answer === null || answer === '') {
					this.$set(this.qidArr[subindex].config, qindex, false)
				} else {
					this.$set(this.qidArr[subindex].config, qindex, true)
				}

				this.$set(this.qidArr[subindex].answer, qindex, answer)
				this.$api.Examination.PaperSubmitSingle({
					id: eqid,
					answer
				})
			},
			goBack() {

				if (this.paperstatus === 0) {
					this.tipmain.openmask = true
					this.tipmain.dialogStatus = true
				} else {
					this.cancel()
					this.$router.back()
				}
			},
			submitAll() {
				this.tipmain.openmask = true
				this.tipmain.submitTip = true
			},
			cancel() {
				this.tipmain.openmask = false
				this.tipmain.submitTip = false
				this.tipmain.readTip = false
				this.tipmain.dialogStatus = false
			},
			submitHandle() {
				let qarr = this.qidArr
				qarr.map((item, index) => {
					let tarr = {}
					item.qunionids.map((it, ind) => {
						tarr[it] = item.answer[ind]
					})
					item.answers = tarr
				})
				this.$api.Examination.PaperSubmit({ examRecordId: this.$route.query.id, answerPaperList: qarr })
					.then(res => {
						this.paperstatus = 1
						this.tipmain.submitTip = false
						this.tipmain.readTip = true
					})
					.catch(e => {
						this.$message.error(e.msg)
					})
			},
			ok() {
				this.tipmain.openmask = false
				this.tipmain.submitTip = false
				this.tipmain.readTip = false
				setTimeout(() => {
					this.$router.back()
				}, 500)
			},
			confirm() {
				this.cancel()
				this.$router.back()
			},
			finish() {
				if (this.paperstatus === 0) {
					this.submitHandle()
				}
			}
		},
	}
</script>
<style lang="less" scoped>
	.content {
		width: 100%;
		height: 100vh;
		padding-bottom: 0;

		.navheader {
			// position: sticky;
			// top: 0;
			z-index: 20;
			width: 100%;
			height: 70px;
			background: #ffffff;

			.top {
				width: 1200px;
				height: 70px;
				margin: 0 auto;
				font-size: 16px;
				font-weight: 500;
				color: #333333;
				line-height: 16px;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				background-color: #fff !important;

				.top-left {
					display: flex;
					flex-direction: row;
					align-items: center;
					cursor: pointer;

					.icon-back {
						width: 24px;
						height: 24px;
						margin-right: 10px;
						cursor: pointer;
					}
				}

				.top-right {
					display: flex;
					flex-direction: row;
					align-items: center;

					.score {
						height: 24px;
						font-size: 24px;
						font-weight: 600;
						color: #333333;
						line-height: 24px;
						margin-right: 50px;
					}

					.score-info {
						height: 16px;
						font-size: 16px;
						font-weight: 400;
						color: #666666;
						line-height: 16px;
						margin-right: 30px;
					}

					.remaining-time {
						height: 16px;
						font-size: 16px;
						font-weight: 400;
						color: #666666;
						line-height: 16px;
						margin-right: 50px;
					}

					.button {
						width: 104px;
						height: 40px;
						background: #3ca7fa;
						border-radius: 4px;
						cursor: pointer;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 16px;
						font-weight: 400;
						color: #ffffff;
					}

					.buttonover {
						width: 104px;
						height: 40px;
						background: #ccc;
						border-radius: 4px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 16px;
						font-weight: 400;
						color: #ffffff;
					}
				}
			}
		}

		.project-box {
			width: 1200px;
			height: calc(100vh - 85px);
			margin: 15px auto 0;
			// display: flex;
			// flex-direction: row;

			.left-box {
				// width: 300px;
				height: 100%;
				background: #ffffff;
				// margin-right: 30px;
				overflow: hidden;
				position: relative;
				float: left;
				transition: all 0.4s ease;

				.left-boxdiv {
					width: 300px;
					height: 100%;
					position: absolute;
					overflow-y: auto;

					.btns {
						width: 100%;
						display: flex;
						flex-direction: row;
						align-items: center;
						justify-content: center;
						height: 50px;
						border-bottom: 1px dotted #ccc;

						.btntitle {
							font-size: 16px;
							font-weight: 400;
							color: #666666;
							font-weight: bold;
						}
					}
				}
			}

			.right-box {
				float: right;
				box-sizing: border-box;
				background-color: #ffffff;
				height: 100%;
				// overflow: hidden;
				// flex: 1;
				display: flex;
				flex-direction: column;
				position: relative;
				transition: all 0.4s ease;

				.tosmbtn {
					position: absolute;
					width: 20px;
					height: 30px;
					left: -20px;
					top: calc(50vh - 80px);
					background-color: #fff;
					// border:1px solid #888;
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 20px;
					color: #888;

					&:hover {
						color: #3ca7fa;
						font-size: 30px;
						font-weight: bold;
					}
				}

				.btns {
					width: 100%;
					display: flex;
					flex-direction: row;
					align-items: center;
					height: 50px;
					border-bottom: 1px dotted #ccc;

					.btn-title {

						height: 100%;
						cursor: pointer;
						line-height: 50px;
						padding: 0 8px;
						// display: flex;
						// flex-direction: column;
						// justify-content: space-between;
						font-size: 14px;
						font-weight: 400;
						color: #666666;
						margin: 0 20px;

						&:last-child {
							margin-right: 0px;
						}

						&.active {
							color: #3ca7fa;
							font-weight: 600;
							border-bottom: 3px solid #3ca7fa;
						}

						&:hover {
							color: #3ca7fa;
						}
					}
				}

				.questions-box {
					width: 100%;
					flex: 1;
					overflow-y: auto;

					.tabtitle {
						padding: 20px 30px 0;
						font-size: 18px;
						font-weight: 500;
						color: #666666;
					}

					.nextbutton {
						width: 184px;
						height: 40px;
						background: #3ca7fa;
						border-radius: 4px;
						cursor: pointer;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 16px;
						font-weight: 400;
						color: #ffffff;
						margin: 30px auto;
					}

					.item {
						width: 100%;
						height: auto;
						float: left;
						position: relative;

						.collect-icon {
							position: absolute;
							width: 28px;
							height: 28px;
							cursor: pointer;
							right: 30px;
							top: 30px;
							z-index: 10;
						}
					}
				}

				.buttons-box {
					width: 100%;
					padding: 30px;
					margin-top: 30px;
					box-sizing: border-box;
					display: flex;
					flex-direction: row;
					align-items: center;

					.see-answer {
						width: 104px;
						height: 40px;
						background: #ff5068;
						border-radius: 4px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 16px;
						cursor: pointer;
						font-weight: 400;
						color: #ffffff;
					}
				}
			}
		}


		.mask {
			width: 100%;
			height: 100%;
			position: fixed;
			top: 0;
			left: 0;
			background-color: rgba(0, 0, 0, 0.6);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1001;

			.popup {
				width: 500px;
				height: 300px;
				background: #ffffff;
				border-radius: 8px;
				display: flex;
				flex-direction: column;
				animation: scaleBig 0.3s;

				.tabs {
					width: 100%;
					height: auto;
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: space-between;
					position: relative;
					padding: 23px 23px 0px 30px;
					overflow: hidden;

					.item-tab {
						width: 72px;
						height: 18px;
						font-size: 18px;
						font-weight: 500;
						color: #333333;
						line-height: 18px;
						margin-top: 7px;
					}

					.btn-close {
						width: 19px;
						height: 19px;
						cursor: pointer;

						&:hover {
							opacity: 0.8;
							animation: rotate360 1s;
						}
					}
				}

				.text {
					width: 100%;
					height: 178px;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 16px;
					font-weight: 400;
					color: #333333;
					line-height: 18px;
				}

				.button {
					width: 100%;
					height: 74px;
					background: #ffffff;
					box-shadow: 0px -1px 5px 0px rgba(0, 0, 0, 0.1);
					border-radius: 0px 0px 8px 8px;
					display: flex;
					flex-direction: row-reverse;
					align-items: center;

					.cancel {
						width: 88px;
						height: 44px;
						border-radius: 4px;
						border: 1px solid #cccccc;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 14px;
						font-weight: 400;
						color: #666666;
						cursor: pointer;
						margin-right: 30px;

						&:hover {
							opacity: 0.8;
						}
					}

					.confirm {
						width: 88px;
						height: 44px;
						background: #3ca7fa;
						border-radius: 4px;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 14px;
						font-weight: 400;
						color: #ffffff;
						cursor: pointer;
						margin-right: 30px;

						&:hover {
							opacity: 0.8;
						}
					}
				}
			}
		}
	}
</style>
